package rise.ui;

import rise.message.Login;
import rise.message.Registration;
import rise.net.LoginTask;
import rise.net.OlivawPortsClient;
import rise.net.ReceiverService;
import rise.net.RegistrationTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class AccessActivity extends RiseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_access);
	}

	@Override
	public void onBackPressed() {
		ReceiverService receiverService = ReceiverService.obtainReceiverService();
		if(receiverService == null || !receiverService.isRunning()){
			super.exitFromRise();
			return;
		}
		super.onBackPressed();
	}
	public void submitRegistration(View v) {
		EditText usernameEditText = (EditText) this
				.findViewById(R.id.accessUsername);
		EditText passwordEditText = (EditText) this
				.findViewById(R.id.accessPassword);

		String username = usernameEditText.getText().toString();
		String password = passwordEditText.getText().toString();

		if (!this.checkUsername(username) || !this.checkPassword(password)) {
			this.stopAccess();
			return;
		}

		Registration registration = new Registration(username, password,
				OlivawPortsClient.getInputPort(), 0, 0);

		RegistrationTask registrationTask = new RegistrationTask(this,
				registration, this);
		registrationTask.execute(new Void[0]);
	}

	public void submitLogin(View v) {
		EditText usernameEditText = (EditText) this
				.findViewById(R.id.accessUsername);
		EditText passwordEditText = (EditText) this
				.findViewById(R.id.accessPassword);

		String username = usernameEditText.getText().toString();
		String password = passwordEditText.getText().toString();

		if (!this.checkUsername(username) || !this.checkPassword(password)) {
			this.stopAccess();
			return;
		}

		Login login = new Login(username, password,
				OlivawPortsClient.getInputPort(), 0, 0);

		LoginTask loginTask = new LoginTask(this, login, this, false);
		loginTask.execute(new Void[0]);
	}

	private boolean checkUsername(String username) {
		if (username == null || username.length() == 0)
			return false;
		for (int i = 0; i < username.length(); i++) {
			char x = username.charAt(i);
			if (!Character.isLetterOrDigit(x))
				return false;
		}
		return true;
	}

	private boolean checkPassword(String password) {
		return this.checkUsername(password);
	}

	private void stopAccess() {
		Toast toast = Toast.makeText(this,
				"Username e/o password invalide. [a-zA-Z0-9]",
				Toast.LENGTH_SHORT);
		toast.show();
	}

	@Override
	void changeStatusToBusy() {
	}

	@Override
	void changeStatusToOnline() {
	}

	@Override
	void logout() {
		super.exitFromRise();
	}

	@Override
	void exit() {
		super.exitFromRise();
	}

	@Override
	protected void onResume() {
		super.superDotOnResume();
	}
	
	@Override
	protected void onRestart() {
		super.superDotOnRestart();
	}

}
